import Qs from 'qs'
import axios from 'axios'
import store from '@/system/store'
import {notification} from 'ant-design-vue'
import { VueAxios } from './axios'

const request = axios.create({
    baseURL: process.env.VUE_APP_API_BASE_URL,
    timeout: 6000
})

request.interceptors.request.use(config => {
    config.withCredentials = true;
    if (config.method.toLowerCase() === 'post' && config.data && config.data.constructor === Object) {
        config.data = Qs.stringify(config.data);
    }
    return config
}, () => {
    notification.error({
        message: '请求失败',
        description: '请求超时，请检查网络'
    });
});

request.interceptors.response.use((data) => {
    if (data) {
        if (data.status === 200) {
            data = data.data;
            if (data.errCode === 0) return data;
            if (data.errCode === 401) store.router.push({path: '/auth/login', replace: true});
            else if (data.errMsg)
                notification.error({
                    message: '错误',
                    description: data.errMsg
                });
            if (data.traceId) console.error('traceId: ' + data.traceId);
        }
        else notification.error({
                message: '错误',
                description: data.statusText || '未知错误'
            });

    }
    return null;
}, (error) => {
    notification.error({
        message: '错误',
        description: '请求失败'
    });
    if (error.response) console.error(error);
    return Promise.reject(error)
})

const installer = {
    vm: {},
    install (Vue) {
        Vue.use(VueAxios, request)
    }
}

export default request

export {
    installer as VueAxios,
    request as axios
}
